<template>
  <div class="detail_container">
    <div class="close" @click="goBack">
      <Close @close="goBack" :size="18" />
    </div>
    <!-- 详情内容 -->
    <div class="content">
      <div class="content-container">
        <!-- 标题 -->
        <div class="head">
          <div class="head-left">
            <div class="title">
              <span>{{ detailModel.createdAt }}</span>
              <span class="bold">{{ detailModel.genTypeName }}</span>
              <span>{{ detailModel.genName }}</span>
            </div>
            <div class="indicator">
              <span>{{ currentIndex + 1 }}/{{ detailModel.carouselItems.length }}</span>
            </div>
          </div>
          <div class="head-right">
            <el-tooltip effect="dark" content="Download" placement="top">
              <DownloadIcon class="svg-icon" @click="downloadFile" />
            </el-tooltip>
            <el-tooltip effect="dark" content="Delete" placement="top">
              <DeleteIcon class="svg-icon" @click="deleteGenerateImg" />
            </el-tooltip>
            <div class="post-text" @click="publishImage">
              <span class="line" v-slide-underline>Post Now</span>
              <PostIcon class="svg-icon" />
            </div>
          </div>
        </div>
        <div class="detail">
          <!-- 轮播图 -->
          <div class="detail-left">
            <el-carousel
              trigger="click"
              class="carousel"
              height="100%"
              :show-indicators="true"
              :indicator-position="'none'"
              :autoplay="false"
              @change="handleCurrentChange"
              ref="carouselRef">
              <el-carousel-item
                class="item"
                v-for="(item, index) in detailModel.carouselItems"
                :key="index">
                <img :src="item.image" :alt="item.alt" class="image" />
              </el-carousel-item>
            </el-carousel>
          </div>
          <div class="detail-right">
            <div class="top-img">
              <img
                :src="item.image"
                :alt="item.alt"
                class="image"
                v-for="(item, index) in detailModel.carouselItems"
                :key="index"
                :class="{ highlight: currentIndex === index }"
                @click="handleTopImgClick(index)" />
            </div>
            <!-- 活动编号 -->
            <div class="contest line" v-if="isAid" v-slide-underline @click="goToContestDetail">
              # {{ contestModel.title }}
            </div>
            <div class="title">
              <el-tooltip effect="dark" content="Copy" placement="top">
                <span class="line" v-slide-underline @click="copyPrompt">Prompt</span>
              </el-tooltip>
            </div>
            <div class="desc">{{ detailModel.prompt }}</div>
            <div v-if="detailModel.referImg">
              <div class="title">Reference Diagram</div>
              <div class="refer">
                <img :src="detailModel.referImg" alt="" />
              </div>
            </div>
            <!-- 图片编辑操作 -->
            <div class="edit">
              <div class="title">Image Editing</div>
              <div class="actions">
                <div class="action-item" @click="goImgPage">
                  <SvgIcon name="ai-detail-img" />
                  <span>For reference</span>
                </div>
                <div class="action-item" @click="goEditPage">
                  <SvgIcon name="ai-detail-edit" />
                  <span>Edit Image Details</span>
                </div>
                <div class="action-item" @click="goHdPage">
                  <SvgIcon name="ai-detail-hd" />
                  <span>Upscale</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import Close from '@/components/Close.vue';
  import { useRoute, useRouter } from 'vue-router';
  import 'swiper/css';
  import { ref, onMounted, reactive, computed } from 'vue';
  import SvgIcon from '@/components/SvgIcon.vue';
  import { AiAPI } from '@/api/ai';
  import { bus } from '@/utils/bus';
  import { dayjs, ElMessage, ElMessageBox } from 'element-plus';
  import { AIType } from '@/types/ai';
  import { downloadImage } from '@/utils/tools';
  import { ActivityAPI } from '@/api/activity';
  import DownloadIcon from '@/components/icons/ai/DownloadIcon.vue';
  import DeleteIcon from '@/components/icons/ai/DeleteIcon.vue';
  import PostIcon from '@/components/icons/ai/PostIcon.vue';
  import { sendGAEvent } from '@/utils/ga4';

  const router = useRouter();
  const route = useRoute();

  // 轮播图组件引用
  const carouselRef = ref<any>(null);
  // 当前轮播图索引
  const currentIndex = ref(0);

  const detailModel = reactive<any>({
    genName: '',
    genTypeName: '',
    prompt: '',
    referImg: '',
    createdAt: '',
    carouselItems: [],
  });

  // 参加活动
  const isAid = computed(() => !!router.currentRoute.value.query.aid);
  const contestModel = ref<any>({});

  // 处理轮播图索引变化
  const handleCurrentChange = (index: number) => {
    currentIndex.value = index;
  };

  // 处理top-img点击事件
  const handleTopImgClick = (index: number) => {
    currentIndex.value = index;
    if (carouselRef.value) {
      carouselRef.value.setActiveItem(index);
    }
  };

  // 返回上一页
  function goBack() {
    router.back();
  }

  // 跳转图生图页面
  const goImgPage = () => {
    const selectedImage = detailModel.carouselItems[currentIndex.value];
    if (!selectedImage) {
      return;
    }

    // GA4 埋点
    sendGAEvent('resultAction', {
      sourcePage: 'nexLab',
      elementID: 'image2image',
    });

    router.push({
      path: '/generator/img2img',
      query: {
        img: encodeURIComponent(selectedImage.image),
      },
    });
  };

  const goEditPage = () => {
    const selectedImage = detailModel.carouselItems[currentIndex.value];
    if (!selectedImage) {
      return;
    }

    // GA4 埋点
    sendGAEvent('resultAction', {
      sourcePage: 'nexLab',
      elementID: 'editImage',
    });

    router.push({
      path: '/generator/edit',
      query: {
        img: encodeURIComponent(selectedImage.image),
      },
    });
  };

  // 跳转超分页面
  const goHdPage = () => {
    const selectedImage = detailModel.carouselItems[currentIndex.value];
    if (!selectedImage) {
      return;
    }

    // GA4 埋点
    sendGAEvent('resultAction', {
      sourcePage: 'nexLab',
      elementID: 'upscale',
    });

    router.push({
      path: '/generator/hd',
      query: {
        img: encodeURIComponent(selectedImage.image),
      },
    });
  };

  // 根据路由中的img_id参数自动选择对应的图片
  const selectImageByImgId = () => {
    // 检查是否有img_id参数
    const imgIdFromRoute = route.query.img_id as string;
    if (!imgIdFromRoute || !detailModel.carouselItems || detailModel.carouselItems.length === 0) {
      return;
    }

    // 查找与img_id匹配的图片索引
    const targetIndex = detailModel.carouselItems.findIndex(
      (item: any) => item.img_id === imgIdFromRoute
    );

    // 如果找到匹配的图片，更新轮播图显示
    if (targetIndex !== -1) {
      currentIndex.value = targetIndex;
      // 延迟设置轮播图，确保DOM已经渲染
      setTimeout(() => {
        if (carouselRef.value) {
          carouselRef.value.setActiveItem(targetIndex);
        }
      }, 0);
    }
  };

  const fetchTaskDetail = async () => {
    const taskId = route.query.task_id as string;
    const response = await AiAPI.generateTaskDetail({ task_id: taskId });
    detailModel.createdAt = dayjs(response.data.created_at).format('YYYY-MM-DD HH:mm:ss');
    detailModel.genTypeName =
      response.data.gen_template.gen_type == AIType.TEXT ? 'Text to Image' : 'Image to Image';
    detailModel.genName = response.data.gen_template.name || '';
    detailModel.carouselItems = response.data.result_imgs?.map((img: any, index: number) => ({
      img_id: img.img_id,
      image: img.img_url,
      alt: `Design Image ${index + 1}`,
      task_id: response.data.task_id,
    }));
    detailModel.prompt = response.data.prompt_text || '';
    detailModel.referImg = response.data.img || '';

    // 调用抽取的函数来处理img_id参数
    selectImageByImgId();
  };

  // 复制提示词到剪切板
  const copyPrompt = async () => {
    try {
      await navigator.clipboard.writeText(detailModel.prompt);
      ElMessage.success('copy success');
    } catch (err) {
      console.error('复制失败:', err);
      ElMessage.error('copy failed, please try again');
    }
  };

  // 发布图片
  const publishImage = () => {
    // 获取当前选中的图片项
    const selectedImage = detailModel.carouselItems[currentIndex.value];
    if (selectedImage && selectedImage.image) {
      // 将当前选中的图片URL传递给发布弹窗
      bus.emit('open:post', {
        image: selectedImage.image,
        prompt: detailModel.prompt,
        contestTitle: contestModel.value.title || '',
      });
    } else {
      // 如果没有选中的图片，显示提示
      ElMessage.warning('Please select the picture you want to post first');
    }
  };

  // 下载图片
  const downloadFile = () => {
    const selectedImage = detailModel.carouselItems[currentIndex.value];
    if (selectedImage && selectedImage.image) {
      downloadImage(selectedImage.image);
      // GA4 埋点
      sendGAEvent('resultAction', {
        sourcePage: 'nexLab',
        elementID: 'download',
      });
    } else {
      ElMessage.warning('Please select the picture you want to download first');
    }
  };

  // 删除生成图片
  const deleteGenerateImg = async () => {
    try {
      // 显示确认对话框
      await ElMessageBox.confirm(
        'Deleting this image will remove it permanently and clear all drawn masks',
        'Delete this image?',
        {
          confirmButtonText: 'Delete',
          cancelButtonText: 'Cancel',
          center: true,
          showClose: false,
          customClass: 'delete-confirm-dialog',
        }
      );

      const currentImage = detailModel.carouselItems[currentIndex.value];

      if (!currentImage) {
        ElMessage.warning('Please select an image to delete');
        return;
      }

      const tasks = [
        {
          task_id: currentImage.task_id,
          img_ids: [currentImage.img_id],
        },
      ];

      await AiAPI.deleteGenerateImg({
        tasks,
      });

      detailModel.carouselItems.splice(currentIndex.value, 1);
      ElMessage.success('Image deleted successfully');
    } catch (error) {}
  };

  // 获取活动详情的方法
  const getActivityDetail = async () => {
    // 检查是否有aid参数
    if (!isAid.value) return;

    // 获取aid参数值
    const aid = route.query.aid as string;

    // 调用API获取活动详情
    const response = await ActivityAPI.getActivityDetail({ aid });

    // 将获取到的活动详情数据赋值给contestModel
    contestModel.value = response.data;
  };

  // 组件挂载时获取任务详情和活动详情
  onMounted(() => {
    fetchTaskDetail();
    getActivityDetail(); // 添加获取活动详情的调用
  });

  // 在script setup部分添加以下方法
  // 跳转到活动详情页
  const goToContestDetail = () => {
    // 确保有活动ID参数
    if (!isAid.value || !route.query.aid) {
      return;
    }

    // 跳转到活动详情页，传递活动ID
    router.push({
      path: '/contest/detail',
      query: {
        aid: route.query.aid,
      },
    });
  };
</script>

<style lang="scss" scoped>
  @use '@/styles/mixins' as *;

  .detail_container {
    position: fixed;
    width: 100vw;
    height: 100vh;
    bottom: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.8);
    z-index: 100;

    .close {
      display: flex;
      flex-direction: row-reverse;
      padding: 20px 41px;
      cursor: pointer;
    }
  }

  .content {
    background: #fff;
    width: 100%;
    height: 100%;
    overflow: auto;
    padding: 40px 260px 140px;

    border-radius: 12px 12px 0 0;

    .content-container {
      margin: 0 auto;
    }

    .head {
      display: flex;
      justify-content: space-between;
      margin-bottom: 16px;
      .head-left {
        width: 50%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .title {
          font-weight: 500;
          font-style: Medium;
          font-size: 14px;
          line-height: 100%;
          letter-spacing: 0%;
          color: #7a7a7a;
          background-color: #ededed;
          padding: 8px 4px;
          border-radius: 8px;
          span {
            padding: 0 8px;
          }
          .bold {
            color: #222222;
            border-left: 1px solid #cbcbcb;
            border-right: 1px solid #cbcbcb;
          }
        }
        /* 数字指示器样式 */
        .indicator {
          width: 50px;
          height: 32px;
          font-size: 14px;
          color: #7a7a7a;
          background-color: #ededed;
          border-radius: 8px;
          display: flex;
          justify-content: center;
          align-items: center;
        }
      }
      .head-right {
        flex: 1;
        display: flex;
        justify-content: flex-end;
        align-items: center;
        .svg-icon {
          margin-right: 16px;
          cursor: pointer;
          &:last-child {
            margin-right: 0;
          }
        }
        .post-text {
          display: flex;
          align-items: center;

          font-weight: 500;
          font-style: Medium;
          font-size: 16px;
          line-height: 100%;
          letter-spacing: 0%;
          color: #222222;
          border-left: 1px solid #cbcbcb;
          padding-left: 16px;
          cursor: pointer;
          span {
            margin-right: 4px;
          }
          &:hover {
            :deep(.v-slide-underline__underline) {
              width: 100%;
            }
            .svg-icon {
              color: #222222;
            }
          }
        }
      }
    }
    .detail {
      display: flex;
      .detail-left {
        width: 50%;
        .carousel {
          width: 100%;
          aspect-ratio: 1 / 1;
          border-radius: 8px;
          overflow: hidden;
          img {
            width: 100%;
            height: 100%;
            object-fit: contain;
          }

          :deep(.el-carousel__arrow) {
            background-color: rgba(0, 0, 0, 0.32);
            width: 40px;
            height: 40px;
            transition: all 0.3s ease;
            &:hover {
              background-color: rgba(0, 0, 0, 0.56);
            }
            .el-icon {
              width: 20px;
              height: 20px;
            }
            .el-icon svg {
              width: 20px;
              height: 20px;
            }
          }
        }
      }
      .detail-right {
        flex: 1;
        padding-left: 32px;
        .top-img {
          display: grid;
          grid-template-columns: repeat(4, 1fr);
          margin-bottom: 24px;
          gap: 8px;
          img {
            width: 100%;
            aspect-ratio: 1 / 1;
            border-radius: 8px;
            object-fit: cover;
            cursor: pointer;
            transition: border 0.3s ease;
            border: 2px solid transparent;
            &.highlight {
              border: 2px solid #f76b1b;
            }
          }
        }
        .contest {
          display: inline-block;
          font-weight: 500;
          font-style: Medium;
          font-size: 16px;
          margin-bottom: 24px;
        }
        .title {
          font-weight: 500;
          font-size: 16px;
          line-height: 150%;
          letter-spacing: 0%;
          color: #222222;
          margin-bottom: 8px;
        }
        .desc {
          font-weight: 400;
          font-size: 16px;
          letter-spacing: 0%;
          margin-bottom: 14px;
          color: #7a7a7a;
        }
        .refer {
          margin-bottom: 48px;
          img {
            width: 80px;
            height: 80px;
            border-radius: 8px;
            object-fit: cover;
          }
        }
        .edit {
          border-top: 1px solid #ededed;
          padding-top: 24px;
          .actions {
            display: flex;
            gap: 16px;
            flex-wrap: wrap;
            .action-item {
              width: 184px;
              height: 40px;
              display: flex;
              align-items: center;
              justify-content: center;
              gap: 8px;
              border-radius: 8px;
              cursor: pointer;
              background: #ededed;

              font-weight: 400;
              font-style: Regular;
              font-size: 16px;
              line-height: 100%;
              letter-spacing: 0%;
              white-space: nowrap;
              &:hover {
                background: #e1e2e3;
              }
            }
          }
        }
      }
    }
  }

  .line {
    display: inline-block;
    background-image: linear-gradient(to right, #cbcbcb, #cbcbcb);
    background-size: 100% 2px;
    background-position: bottom;
    background-repeat: no-repeat;
    padding-bottom: 2px;
  }
</style>
